package com.jsoup.controller;

import com.jsoup.bean.User;
import com.jsoup.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
public class GetBackPwdController {

    @Resource
    private UserService userService;

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sendUserName;

    @RequestMapping(value = "/getBackPassword", method = RequestMethod.GET)
    public String getBackPassword() {
        return "getback-password";
    }

    /**
     * 找回密码
     *
     * @param userEmail
     * @param userPassword
     * @return
     */
    @RequestMapping(value = "/getBackPassword", method = RequestMethod.POST)
    @ResponseBody
    public Object getBackPassword(@RequestParam(value = "userEmail") String userEmail,
                                  @RequestParam(value = "userPassword") String userPassword) {
        Map<Object, Object> map = new HashMap<>();
        User u = new User();
        u.setUserEmail(userEmail);
        User user = userService.getUser(u);
        Md5Hash md5UserPassword = new Md5Hash(userPassword, ByteSource.Util.bytes(user.getUserName()), 1024);
        user.setUserPassword(md5UserPassword.toString());
        int count = userService.updateByPrimaryKeySelective(user);
        if (count > 0) {
            map.put("result", "success");
        }
        return map;
    }

    /**
     * 发送验证码到邮箱
     *
     * @param userEmail
     * @return
     */
    @RequestMapping("/getJavaMailSender")
    @ResponseBody
    public Object getJavaMailSender(@RequestParam(value = "userEmail") String userEmail) {
        Map<Object, Object> map = new HashMap<>();
        User u = new User();
        u.setUserEmail(userEmail);
        User user = userService.getUser(u);
        if (user != null) {
            int randomCode = (int) ((Math.random() * 9 + 1) * 1000);
            SimpleMailMessage mainMessage = new SimpleMailMessage();
            mainMessage.setFrom(sendUserName);
            mainMessage.setTo(userEmail);
            mainMessage.setSubject("汤海鸿个人博客");
            mainMessage.setText("亲爱的博友： 您好! 您正在修改安全邮箱，请在验证码输入框中输入： " + randomCode + "，以完成操作。此为系统邮件，请勿回复");
            try {
                javaMailSender.send(mainMessage);
                map.put("code", randomCode);
            } catch (Exception e) {
                map.put("message", "该邮箱接收邮件异常");
            }
        } else {
            map.put("message", "邮箱未注册");
        }
        return map;
    }
}
